package service

import (
	"fmt"
	"push/config/table"
	"strconv"

	//"github.com/go-redis/redis/v8"
	"push/global"

	//"strconv"

	"github.com/garyburd/redigo/redis"
	"sync"
	"time"
)

var lockKey = "lock:counter_lock_"
var counterKey = "1lock:counter_"



var conn redis.Conn
var expire = time.Now().Unix()+5
var nowtime int64

var (
	// 定义常量
	RedisClient     *redis.Pool
)

func initx() {
	// 从配置文件获取redis的ip以及db
	redisCFG := global.GLOBAL_REDIS
	// 建立连接池
	RedisClient = &redis.Pool{
		// 从配置文件获取maxidle以及maxactive，取不到则用后面的默认值
		MaxIdle:     1,
		MaxActive:   150,
		IdleTimeout: 180 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", redisCFG.Host)
			if err != nil {
				return nil, err
			}
			if _, err := c.Do("AUTH", redisCFG.Pwd); err != nil {
				fmt.Println(err)
			}
			// 选择db
			c.Do("SELECT", redisCFG.DB)
			return c, nil
		},
	}
}

func RedisConnx() redis.Conn{
	redisCFG := global.GLOBAL_REDIS
	c, err := redis.Dial("tcp", redisCFG.Host)
	if err != nil {
		fmt.Println(err)
	}
	if _, err := c.Do("AUTH", redisCFG.Pwd); err != nil {
		fmt.Println(err)
	}
	if _, err := c.Do("SELECT", redisCFG.DB); err != nil {
		c.Close()
		fmt.Println(err)
	}
	return c
}

func handleQueue(){
	//c := RedisConnx()
	c := RedisClient.Get()
	if(lock(c)){
		//fmt.Println("开始发送红包")
	}
	defer c.Close()
}

func lock(c redis.Conn) bool{
	queue_value ,err := redis.String(c.Do("LPOP", table.Redis_table_hongbao_list))
	//fmt.Println(queue_value)
	if(queue_value ==""){return false}
	queue_table := fmt.Sprintf("%s%s", lockKey,queue_value)
	lockSuccess, err := c.Do("SETNX",queue_table,expire)
	//fmt.Printf("v1 type:%T\n", lockSuccess)
	if(err != nil || lockSuccess == int64(0) ){
		c.Do("LPUSH", table.Redis_table_hongbao_list,queue_value)
		ntime ,err := redis.String(c.Do("GET",queue_table))
		if(err != nil){fmt.Println(err)}
		t, err := strconv.ParseInt(ntime, 10, 64)
		if(t < time.Now().Unix()){
			fmt.Println( fmt.Sprintf("%s%s过期", lockKey,queue_value) )
			unlock(c,queue_value)
			//$is_lock=$redis->setnx($key,time()+$expire);
		}
		return false
	}
	unlock(c,queue_value)
	send(queue_value)
	return true
}
func send (value string){
 fmt.Println(fmt.Sprintf("开始发放红包%s", value))
}

func unlock(c redis.Conn,value string) bool{
	if _, err := c.Do("DEL", fmt.Sprintf("%s%s", lockKey,value)); err != nil {
		fmt.Println( fmt.Sprintf("%s%s解锁失败", lockKey,value) )
		return false
	}
	//fmt.Println( fmt.Sprintf("%s%s解锁成功", lockKey,value) )
	return true
}

func Ceshi() {

	var wg sync.WaitGroup
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			handleQueue()
		}()
	}
	wg.Wait()

}

func Start (){
	initx()
	var ch chan int
	//定时任务
	ticker := time.NewTicker(time.Second * 1)
	go func() {
		for range ticker.C {
			Ceshi();
			fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
		}
		ch <- 1
	}()
	<-ch
}